var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');
const bodyParser = require('body-parser');
// token相关包导入
const jwt = require('jsonwebtoken');
const expressJWT = require('express-jwt');
// 数据访问相关包导入
const{ Sequelize,DataTypes } = require('sequelize');

var app = express();
//配置跨域中间件
app.use(cors());
//配置表单中间件
const json = express.json({type: '*/json'});
app.use(json);
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

const secretKey = 'justatest'

app.use(expressJWT({
    secret:secretKey,
    algorithms:['HS256']
    })
    .unless({
        path:[
            '/login/check',
            '/user/register'
        ]
    }));
//
//引入路由文件
const indexRouter = require('./routes/index');
const loginRouter = require('./routes/login');
const usersRouter = require('./routes/user');
const orderRouter = require('./routes/order');
const carRouter = require('./routes/trans');
//注册路由
app.use('/index',indexRouter);
app.use('/user',usersRouter);
app.use('/login',loginRouter);
app.use('/order',orderRouter)
app.use('/car',carRouter)
// 改写
var http = require('http');
var server = http.createServer(app);



app.use((err,req,res,next)=>{
    //token处理
    if(err.name === 'UnauthorizedError'){
        console.log(err);
        return res.send({
            status:401,
            msg:'无效token'
        })
    }
    if(err.name === 'Unauthorized'){
        res.send('用户名或密码输入错误，请重新输入')
    }
    //res.send('出现错误！')

})

// 引用相关插件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname,'image')));

app.listen(3000,()=>console.log('Example app listening on port 3000'))
//不暴露
//module.exports = app;
